package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import com.itheima.reggie.utils.UserThreadLocal;

import com.itheima.reggie.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService cartService;

    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookServicel bookServicel;


    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 生成订单
     *
     * @param orders
     * @return
     */
    @Override
    @Transactional
    public R sumbit(Orders orders) {
        /* 校验传递过来的参数 地址id */
        if (ObjectUtil.isNull(orders.getAddressBookId())) return R.error("数据非法");

        /* 设置订单相关的属性值 */
        /* 设置订单号 */
        /* IdWorker.getId() 使用雪花算法生成一个随机数 */
        orders.setNumber(StrUtil.toString(IdWorker.getId()));
        /* 设置订单状态 默认是4 已完成 */
        orders.setStatus(4);
        /* 设置下单人的id */
        orders.setUserId(UserThreadLocal.get().getId());
        /* 设置下单时间 */
        orders.setOrderTime(LocalDateTime.now());
        /* 设置支付时间 */
        orders.setCheckoutTime(LocalDateTime.now());

        /* 查询当前订单对应的购物车 */
        List<ShoppingCart> cartList = cartService.list(Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, UserThreadLocal.get().getId()));
        /* 订单总金额 */
        BigDecimal amount = new BigDecimal(0d);
        for (ShoppingCart dish : cartList) {
            /* 计算订单的总金额 */
            amount = amount.add(dish.getAmount().multiply(new BigDecimal(dish.getNumber())));
        }

        /* 设置支付金额 */
        orders.setAmount(amount);

        /* 根据addressBookId 查询收货人信息 */
        AddressBook addressBook = bookServicel.getById(orders.getAddressBookId());

        /* 设置收货人手机号码 */
        orders.setPhone(addressBook.getPhone());
        /* 设置收货人地址 */
        orders.setAddress(addressBook.getDetail());
        /* 设置下单人的name/登录人的name */
        orders.setUserName(UserThreadLocal.get().getName());
        /* 设置收获人的名称 */
        orders.setConsignee(addressBook.getConsignee());

        /* 保存订单到数据库 */
        this.save(orders);

        /* 创建订单详情表实体 */
        /* 定义订单详情集合 */
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart dish : cartList) {
            /* 拼凑一个订单详情对象 */
            OrderDetail detail = new OrderDetail();
            /*detail.setName(dish.getName());
            detail.setImage(dish.getImage());
            detail.setSetmealId(dish.getSetmealId());
            detail.setDishFlavor(dish.getDishFlavor());
            detail.setNumber(dish.getNumber());
            detail.setAmount(dish.getAmount());*/
            /* 使用工具类做对象属性的拷贝 */
            BeanUtil.copyProperties(dish, detail, "id");
            detail.setOrderId(orders.getId());
            orderDetails.add(detail);
        }
        /* 把订单详情批量保存到订单详情表中 */
        orderDetailService.saveBatch(orderDetails);

        /* 清空购物车 */

        cartService.cleanCart();
        return R.success("下单成功");
    }

    /**
     * 再来一单
     *
     * @param map
     * @return
     */
    @Override
    public R againShopping(Map<String, String> map) {
        //获取订单id
        String ids = map.get("id");
        long id = Long.parseLong(ids);
        //获取该订单对应的所有的订单明细表
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);

        //获取用户id
        Long userId = UserThreadLocal.get().getId();
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            //把从order表中和order_details表中获取到的数据赋值给这个购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                //如果是菜品那就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
            } else {
                //添加到购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //把携带数据的购物车批量插入购物车表  这个批量保存的方法要使用熟练！！！
        cartService.saveBatch(shoppingCartList);

        return R.success("操作成功");

    }
}